<style>
.layui-input-block{
margin-left:120px;
}
</style>
<form class="layui-form" action="" id="orderEditForm">
<!-- 隐藏域用于传递ID th:value="${order.id}"-->
<input  class="form-control formSubmit layui-hide"  name="companyId" th:value="1"/>
 <div class="layui-row"  style="margin-top:10px;">

	  <div class="layui-col-xs6 layui-col-sm6 layui-col-md6">
	    <label class="layui-form-label" style="width:120px;">来源单号</label>
	    <div class="layui-input-block" style="width:200px;">
<!-- 	          <select lay-verify="required" required name="sourceBillid" lay-filter="sourceBillid"> -->
<!-- 	          	<option value="">请选择</option> -->
	          	
<!-- 	          </select> -->
	 	 <select  style="width:250px;height:58px;" name="sourceBillId" lay-filter="sourceBillId"  >
	      	<option value="">请选择来源单据号</option>
	        <option th:each="s:${purchaseOrders}" th:attr="value=${s.id}" th:text="${s.billNo}" ></option>
	      </select>
	          <input type="hidden" class="layui-input" name="sourceBillNo" value=""/>
	    </div>
	  </div>
  	 
	  <div class="layui-col-xs6 layui-col-sm6 layui-col-md6">
		    <label class="layui-form-label" style="width:120px;">入库单号</label>
		    <div class="layui-input-block" style="width:200px;">
		         <input type="text" name="billNo" class="layui-input" lay-verify="required" value=""/>
		    </div>
	   </div>
  </div>
  
  
 <div class="layui-row" style="margin-top:10px;">
 	<div class="layui-col-xs6 layui-col-sm6 layui-col-md6">
	    <label class="layui-form-label" style="width:120px;">供应商名称</label>
	    <div class="layui-input-block" style="width:200px;">
	      <select style="width:200px;height:58px;" id="supplyId" name="supplyId" lay-verify="required" required lay-ignore>
	      </select>
	    </div>
	</div>
	  
	  <div class="layui-col-xs6 layui-col-sm6 layui-col-md6">
	    <label class="layui-form-label" style="width:120px;" lay-filter="supplierContacts">供应商联系人</label>
	    <div class="layui-input-block" style="width:200px;">
<!-- 	      <select name="connactId" lay-verify="required" required lay-filter="contactId"> -->
<!-- 	       <option th:each="s:${contacts}" th:attr="value=${s.id}" th:text="${s.name}"></option> -->
<!-- 	      </select> -->
			 <select name="supplyContactId" lay-verify="required" required >
<!--        	<option th:each="s:${contacts}" th:attr="value=${s.id}" th:text="${s.name}"></option> -->
      		</select>
	    </div>
	  </div>
  
    
 </div>
 
  <div class="layui-row" style="margin-top:10px;">
  	  <div class="layui-col-xs6 layui-col-sm6 layui-col-md6">
	    <label class="layui-form-label" style="width:120px;" lay-filter="supplierContacts">结算方式</label>
	    <div class="layui-input-block" style="width:200px;">
	      <select name="statementId"  required lay-filter="statementId">
	        <option value="">请选择结算方式</option>
	      </select>
	      <input type="hidden" name="statementName" value=""/>
	      <input type="hidden" name="statementCurrencyId" value=""/>
	    </div>
	  </div>
	  <div class="layui-col-xs6 layui-col-sm6 layui-col-md6">
	    <label class="layui-form-label" style="width:120px;" lay-filter="supplierContacts">结算天数</label>
	    <div class="layui-input-block" style="width:200px;">
	      	<input type="text" readonly="true" name="statementDays" class="layui-input"  style="background-color:#ececec"/>
	    </div>
	  </div>
	  
  </div>
  <div class="layui-row" style="margin-top:10px;">
  	<div class="layui-col-xs6 layui-col-sm6 layui-col-md6">
	    <label class="layui-form-label" style="width:120px;">税率</label>
	    <div class="layui-input-block" style="width:200px;">
	      	<input type="text" readonly="true" name="statementTaxRate" class="layui-input" style="background-color:#ececec"/>
	    </div>
	  </div>
	  
   <div class="layui-col-xs6 layui-col-sm6 layui-col-md6">
    <label class="layui-form-label" style="width:120px;" lay-filter="supplierContacts">汇率</label>
    <div class="layui-input-block" style="width:200px;">
      	<input type="text" readonly="true" name="statementExchangeRate" class="layui-input"  style="background-color:#ececec"/>
    </div>
  </div>
  </div>
  
  <div class="layui-row" style="margin-top:10px;">
	  <div class="layui-col-xs12 layui-col-sm12 layui-col-md12">
	    <label class="layui-form-label" style="width:120px;" lay-filter="supplierContacts">备注</label>
	    <div class="layui-input-block" style="width:200px;">
		    <textarea rows="6" cols="74" name="remark" resize="no"></textarea>
	    </div>
	   </div>
  </div>
  
 <div class="layui-row" style="margin-top:20px;">
    <div class="layui-col-xs12 layui-col-sm12 layui-col-md12" style="text-align:center;">
          <button class="layui-btn" lay-submit="" lay-filter="formSubmit" authcode='900031'>提交</button>
      	<button type="button" class="layui-btn layui-btn-primary" id="closeBtn">关闭</button>
    </div>
  </div>

</form>
<script>
layui.use('form', function(){
	$("[name='supplyId']").select2({
		  placeholder:"请选择供应商",//placeholder 
		  language: 'zh-CN',//中文语言
		  //allowClear:true,//出现删除按钮图片，可以清除下拉选中内容
		  ajax: {
			    url: "/com/supplier/customer/supplierList",
			    dataType: 'json',
			    delay: 350,
			    data: function (params) {
			      console.log(params.page)
			      return {
			        name: params.term, // search term
			        companyid:1,
			        page: params.page,
			        limit:30
			      };
			    },
			    processResults: function (data, params) {
			    $("select[name='supplyId']").html("");//清空
			    $("input[name='statementDays']").val("");
			    $("input[name='statementTaxRate']").val("");
			    $("input[name='statementExchangeRate']").val("");
			    $("input[name='statementCurrencyId']").val("");
			      params.page = params.page || 1;
			      console.log(JSON.stringify(data))
			      return {
			        results: data.data,
			        pagination: {
			          more: (params.page * 30) < data.count
			        }
			      };
			    },
			    cache: true
			  },
			  escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
			  minimumInputLength: 0,//最小输入字符，输入最小字符后开始后台请求
			  templateResult: formatRepo, // 处理远程返回数据
			  templateSelection: formatRepoSelection // 设置下拉选中后显示内容
			});
	  
	  	function formatRepo (repo) {
	  		//下拉展示内容可以修改自定义样式
	      if (repo.loading) return repo.text;
	      var markup = "<div class=\"layui-row\">" +
			      "<div class=\"layui-col-xs4 layui-col-sm4 layui-col-md3\">" +
			      	"<div class=\"grid-demo grid-demo-bg1\">"+repo.no+"</div>" +
			     "</div>"+
			     "<div class=\"layui-col-xs8 layui-col-sm8 layui-col-md9\">" +
			      	"<div class=\"grid-demo grid-demo-bg1\">"+repo.name+"</div>" +
			     "</div>";

	      return markup;
	    }

	    function formatRepoSelection (repo) {
	    	if(repo.name==null || repo.name=='') {
	    		return repo.text;
	    	}
	      return repo.name;//选中返回select中的值
	    }
	
	  var form = layui.form; //只有执行了这一步，部分表单元素才会自动修饰成功
	  //……
	  //但是，如果你的HTML是动态生成的，自动渲染就会失效
	  //因此你需要在相应的地方，执行下述方法来手动渲染，跟这类似的还有 element.init();
	  form.render();
	 /*  form.on('select(supplierName)', function(data){
		  console.log(data.elem); //得到select原始DOM对象
		  console.log(data.value); //得到被选中的值
		  console.log(data.othis); //得到美化后的DOM对象
		  $.getJSON("/com/suppliercustomer/contacts/"+data.value,function(data){
			  var html = [];
			  html.push("<option value=''>请选择联系人</option>")
			  $.each(data,function(i,item){
				  html.push("<option value='"+item.id+"'>"+item.name+"</option>")
			  })
			  $("select[name='contacts']").html(html.join(""));
              form.render('select'); //这个很重要
		  });
		}); */
		 //select2选中事件
		  $("[name='supplyId']").on("select2:select",function(e){
			  console.log(e.params)
			  var id = e.params.data.id;
			  console.log(id)
			   //获取税率信息
			  $.getJSON("/stock/inbound/queryTax/"+id+"/"+e.params.data.companyId,function(data){
	              $("input[name='statementTaxRate']").val(data.value);
			  });
			  //联系人
			  $.getJSON("/com/supplier/customer/contacts/"+id,function(data){
				  var html = [];
				  html.push("<option value=''>请选择联系人</option>")
				  $.each(data,function(i,item){
					  html.push("<option value='"+item.id+"' data-phone='"+item.phone+"'>"+item.name+"</option>")
				  })
				  $("select[name='supplyContactId']").html(html.join(""));
	              form.render('select'); //这个很重要
			  });
			  //选择供应商带出供应商结算方式
			  $.getJSON("/stock/inbound/querySettleMethod/"+id,function(data){
				  var html = [];
				  html.push("<option value=''>请选择结算方式</option>")
				  $.each(data,function(i,item){
					  if(item.isDefault==1){
					  	html.push("<option value='"+item.id+"' data-taxRate='"+item.taxRate+"' data-exchangeRate='"+item.exchangeRate
					  			+"' data-currencyId='"+item.currency+"' data-currencyName='"+item.currencyName+"' data-settleDays='"+item.dates+"' selected>"
					  			+item.statementType+"</option>")
					  	  $("input[name='statementDays']").val(item.dates);
						  $("input[name='statementExchangeRate']").val(item.exchangeRate);
						  $("input[name='currencyName']").val(item.currencyName);
						  $("input[name='statementName']").val(item.statementType);
						  $("input[name='statementCurrencyId']").val(item.currency);
					  }else{
							html.push("<option value='"+item.id+"' data-exchangeRate='"+item.exchangeRate
									+"' data-currencyId='"+item.currency+"' data-currencyName='"+item.currencyName+"' data-settleDays='"+item.dates+"'>"
						  			+item.statementType+"</option>")
					  }
				  });
				  
				  //默认显示选中的结算方式信息
				  $("select[name='statementId']").html(html.join(""));
	              form.render('select'); //这个很重要
	              
			  });
			  
		  });
		  //联系人选中监听
		  //带出手机号码
		  form.on("select(supplyContactId)",function(data){
			  var phone = $(data.elem).find("option[value='"+data.value+"']").attr('data-phone');
			  $("input[name='phone']").val(phone);
		  });
		//来源单据号选中事件
		form.on("select(sourceBillId)",function(data) {
			clearData();
			//来源单据号
			 var sourcebillno = $(data.elem).find("option[value='"+data.value+"']").text();
			  $("input[name='sourceBillNo']").val(sourcebillno);
			  //获取来源单号信息
			$.getJSON("/stock/inbound/purchaseOrder/"+data.value,function(data) {
				if(data.code == 200) {
					var data =data.result;
					//供应商联系人
					var str1 = "<option value='"+data.supplierConnactId+"'>"+data.supplierConnact+"</option>";
					$("select[name='supplyContactId']").html("").html(str1);
					//供应商
					var str2 = "<option value='"+data.supplierid+"'>"+data.supplierName+"</option>";
					$("select[name='supplyId']").html(str2);
					
// 					var str3 ="<option value='"+data.statementId+"'>"+data.statementName+"</option>";
					console.log("data.statementId = "+data.statementId+"-"+data.statementName);
					form.render('select');
					//税率
					 $("input[name='statementDays']").val(data.statementDays);
					 $("input[name='statementExchangeRate']").val(data.exRate);//汇率
					 $("input[name='currencyName']").val(data.currencyName);
					 $("input[name='statementName']").val(data.statementName);
					 $("input[name='statementCurrencyId']").val(data.currencyId);
					 $("input[name='statementTaxRate']").val(data.taxRate);
					 //带出结算方式:
					$.getJSON("/stock/inbound/querySettleMethod/"+data.supplierid,function(e){
							  var html = [];
//			 				  html.push("<option value=''>请选择结算方式</option>")
							  $.each(e,function(i,item){
								  console.log("itemid="+item.id+"-"+item.statementType+"data.statementId="+data.statementId);
								  if(item.id == data.statementId) {
										html.push("<option value='"+item.id+"' data-exchangeRate='"+item.exchangeRate
												+"' data-currencyId='"+item.currency+"' data-currencyName='"+item.currencyName+"' data-settleDays='"+item.dates+"' selected>"
									  			+item.statementType+"</option>")
								  }else{
										html.push("<option value='"+item.id+"' data-exchangeRate='"+item.exchangeRate
												+"' data-currencyId='"+item.currency+"' data-currencyName='"+item.currencyName+"' data-settleDays='"+item.dates+"'>"
									  			+item.statementType+"</option>")
								  }
							  });
							  
							  //默认显示选中的结算方式信息
							  $("select[name='statementId']").html(html.join(""));
				              form.render('select'); //这个很重要
				              
						  });
				}else{
					layer.msg(data.message,{icon: 2});
				}
			}); 

		});
		//结算方式选择
		   form.on("select(statementId)",function(data){
			  var $option = $(data.elem).find("option[value='"+data.value+"']");
			  $("input[name='statementDays']").val($option.attr("data-settleDays"));
			  $("input[name='statementExchangeRate']").val($option.attr("data-exchangeRate"));
			  $("input[name='currencyName']").val($option.attr("data-currencyName"));
			  $("input[name='statementName']").val($option.text());
			  $("input[name='statementCurrencyId']").val($option.attr("data-currencyId"));
		  });
		
	  $("#closeBtn").click(function(){
		  layer.close(editdialogindex);
	  })
	  //表格重载，确定当前的页按钮
		function reloadData(){
			$(".layui-laypage-btn")[0].click();//页面的确定按钮
			
		}
	  //清除数据
	  function clearData() {
		  	//税率
		  	$("select[name='statementId']").html("");
		  	$("input[name='statementDays']").val("");
			 $("input[name='statementExchangeRate']").val("");//汇率
			 $("input[name='currencyName']").val("");//币种名称
			 $("input[name='statementName']").val("");
			 $("input[name='statementCurrencyId']").val("");//币种id
			 $("input[name='statementTaxRate']").val("");
			 //供应商
			 $("select[name='supplyContactId']").html("");
			 $("select[name='supplyId']").html("");
	  }
	  //监听提交
	  form.on('submit(formSubmit)', function(data){
// 	    layer.msg(JSON.stringify(data.field));
		var sourceOrderId = $("[name='supplyId']").val();
		if(sourceOrderId=="" ||sourceOrderId ==null ) {
			layer.msg("请选择供应商");
			return false;
		}
	    $.ajax({
            type: "GET",
            url: "/stock/inbound/add",
            data: $("#orderEditForm").serializeJson(),
            dataType: "json",
            success: function(data){
            	if(data.code==200){
            		//关闭弹出层
           	    layer.closeAll(editdialogindex);
           	    //更新表格数据
           	    layer.msg(data.message,{icon: 6});
           	    /* trobj.update(
           	    			data.result
           	    			); */
//            	    ins.reload({
//            	    		url:'/stock/inbound/list',
//            	    		where: {
//            	    			companyId: '1'
//            	    			//reviewStatus: '0'
//            	    		}
//            	    	});
 					reloadData();
            	}else{
            		layer.msg(data.message,{icon: 2});
            	}
            }
           });
	    //关闭
	    layer.close(editdialogindex);
	    //更新表格数据
	    ins.reload
	    return false;
	  });
		 //关闭按钮
		  $("#closeBtn").click(function(){
			  layer.closeAll();
		  })
	});

</script>
